package com.atguigu.rabbitmq.helloworld.Consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    private static final String QUEUE_NAME = "HELLO"; // 设置rabbitmq队列的名称

    private static final String HOST = "127.0.0.1";

    private static final String USERNAME = "admin";

    private static final String PASSWORD = "root";


    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();

        factory.setUsername(USERNAME);

        factory.setPassword(PASSWORD);

        factory.setHost(HOST);

        Connection connection = null;

        Channel channel = null;

        // 定义回调函数：用于处理消费的消息
        DeliverCallback deliverCallback = ((consumerTag, message) -> {
            System.out.println(new String(message.getBody())); //
        });

        // 定义回调函数：如果消费消息被中断时执行的方法
        CancelCallback cancelCallback = (consumerTag -> {
            System.out.println("消费数据失败");
        });

        try {
            connection = factory.newConnection();

            channel = connection.createChannel();

            channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
